package edu.buffalo.cse.cse486_586.simpledynamo;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.StreamCorruptedException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;

import android.util.Log;

public class SendingThread implements Callable<Boolean> {
	// Debug params
	final private String TAG = "SendingThread";
	// final private Boolean isDebug = true;

	private String ip;
	private int port;
	private String pkgStr;
	private boolean isWait;

	public SendingThread(String ip, int port, String str, boolean isWait) {
		this.ip = ip;
		this.port = port;
		this.pkgStr = str;
		this.isWait = isWait;
	}

	@SuppressWarnings("finally")
	@Override
	public Boolean call() {
		Socket s;
		boolean isFinish = true;
		try {
			// s = new Socket(this.ip, this.port);
//			if (isWait)
//				Thread.sleep(3000);
			s = new Socket();
			s.connect(new InetSocketAddress(this.ip, this.port), 1000);

			Log.d(TAG, "send to " + this.port + "===>" + this.pkgStr);
			MyPackage p = new MyPackage(this.pkgStr);
			ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());

			out.writeObject(p);
			out.close();
			s.close();
		} catch (StreamCorruptedException e) {
			Log.e(TAG, "Exception", e);
			isFinish = false;
		} catch (UnknownHostException e) {
			Log.e(TAG, "Exception", e);
			isFinish = false;
		} catch (IOException e) {
			Log.e(TAG, "Exception", e);
			isFinish = false;
		} finally {
			return isFinish;
		}
	}

}
